import {
  GET_SOURCE,
  SOURCES_LIST,
  REMOVE_SOURCES,
  ADD_SOURCES,
  CALLBACK,
  DOWNLOAD_NOVEL,
  GET_NOVEL,
  NOVEL_LIST,
  REMOVE_NOVEL,
  UPDATE_NOVEL,
  GET_NOVEL_CHAPTER,
  CHANG_NOVEL_SOURCE,
  UPDATE_SOURCE,
  SEARCH_NOVEL,
  STOP_SEARCH_NOVEL,
  GEN_MOBI,
  BATCH_ADD_SOURCES
} from './channel'

import qs from 'querystring'

function request (url, options = {}) {
  if(options.body) {
    options.body = JSON.stringify(options.body)
  }
  if(!options.headers) {
    options.headers = {
      ['Content-Type']: 'application/json'
    }
  }
  return fetch('/api' + url, options).then(res => res.json()).then(res => {
    if(res.code === 200) {
      return res.data
    } else {
      return Promise.reject(res)
    }
  })
}

export function getSource (params) {
  return request(GET_SOURCE + '?' + qs.stringify(params))
}

export function batchAddSources(params) {
  return request(BATCH_ADD_SOURCES, { method: 'POST', body: params })
}

export function getSourceList (params) {
  return request(SOURCES_LIST, params)
}

export function removeSource (params) {
  return request(REMOVE_SOURCES, params)
}

export function addSource (params) {
  return request(ADD_SOURCES, { method:'POST', body: params})
}

export function downloadNovel (params) {
  return request(DOWNLOAD_NOVEL, { method: 'POST', body: params })
}

export function getNovel (params) {
  return request(GET_NOVEL.replace(":id", params.id))
}

export function getNovelList (params) {
  return request(NOVEL_LIST, params)
}

export function removeNovel (params) {
  return request(REMOVE_NOVEL, params)
}

export function editNovel (params) {
  return request('/novels', { method: 'PUT', body: params })
}

export function getNovelChapter (params) {
  return request(GET_NOVEL_CHAPTER + '?' + qs.stringify(params))
}

export function updateNovel (params) {
  return request(UPDATE_NOVEL, { method: 'POST', body: params })
}

export function updateSource (params) {
  return request(UPDATE_SOURCE, { method: 'PUT', body: params })
}

export function searchNovel (params) {
  return request(SEARCH_NOVEL + '?' + qs.stringify(params))
}

export function stopSearchNovel (params) {
  return request(STOP_SEARCH_NOVEL, params)
}

export function genMobi (id) {
  return request(GEN_MOBI, id)
}
